<template>
  <div class="message">
    <Header :getGoods="getGoods"  />
    <div class="message-main">
      <div class="message-main-left">
        <el-row class="tac">
          <el-col :span="12">
            <h5 class="mb-2">消息中心</h5>
            <el-menu
              default-active="1"
              class="el-menu-vertical-demo"
              @select="handleSelect"
            >
              <el-menu-item index="1">
                <el-icon><User /></el-icon>
                <span>我的消息</span>
              </el-menu-item>
              <el-menu-item index="2">
                <el-icon><Bell /></el-icon>
                <span>回复我的</span>
              </el-menu-item>
              <el-menu-item index="3">
                <!-- <el-icon><Document /></el-icon> -->
                <span></span>
              </el-menu-item>
              <el-menu-item index="4">
                <!-- <el-icon><Setting /></el-icon> -->
                <span></span>
              </el-menu-item>
            </el-menu>
          </el-col>
        </el-row>
      </div>
      <div class="message-main-right">
        <div class="message-main-right-top">
          {{ selectedMenuText }}
        </div>
        <div class="message-main-right-main">
          <div v-show="isChatRoomVisible">
            <div class="chat-room">
              <div class="chat-room-top">
                {{ selectedContactUsername || '请添加联系人' }}
              </div>
              <div class="chat-room-bot">
                <div class="chat-room-bot-left">
                  <div v-if="contacts && contacts.data.length > 0" class="contacts-item">
                    <li v-for="contact in contacts.data" :key="contact.username" class="contact-item" @click="onContactClick(contact.username,contact.id)">
                      <img :src="contact.avatar" alt="头像" class="contact-avatar" />
                      <div class="name-button">
                        <span class="contact-username">{{ contact.username }}</span>
                       <div class="message-close-button" @click.stop="deleteContact(contact.id)"><el-icon><Close /></el-icon></div> 
                      </div>
                    </li>
                  </div>
                  <div v-else>
                    <p>暂无联系人数据</p>
                  </div>
                </div>
                <div class="chat-room-bot-right">
                  <div class="chat-room-bot-right-top" ref="chatRoomBotRightTop" @scroll="handleScroll">
                        <div v-for="msg in messages" :key="msg.id ?? 'defaultKey'" :class="{'message-right': msg.senderId === loginId, 'message-left': msg.senderId !== loginId}">
                          <p>{{ msg.message }}</p>
                          <span class="message-timestamp">{{ msg.timestamp }}</span>
                        </div>
                    </div>
                  <div class="chat-room-bot-right-bot">
                    <div class="send-message-top">
                      <textarea v-model="message" @keydown="handleKeyDown" class="send-message-input" rows="4" placeholder="输入你的消息..."></textarea>
                    </div>
                    <div class="send-message-bot">
                      <button type="button" class="send-message-button" @click="sendMessage">发送</button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div v-show="isReplyMessageVisible">
            <div class="reply-message">
              <div v-if="replyMessages.length > 0">
                <ul>
                  <li 
                    v-for="comment in replyMessages" 
                    :key="comment.id ?? 'defaultKey'" 
                    class="comment-item"
                    @click="goToDetailPage(comment.goodsId)"
                  >
                    <img :src="comment.avatar" alt="头像" class="message-avatar" />
                    <p><strong>{{ comment.user }}</strong>: {{ comment.content }}</p>
                  </li>
                </ul>
              </div>
              <div v-else>
                <p>暂无回复消息</p>
              </div>
            </div>
          </div>
          <div v-show="isLikesMessageVisible">
            <p>点赞我的消息列表...</p>
          </div>
          <div v-show="isSystemNotificationVisible">
            <p>系统通知列表...</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, nextTick, watch, onUnmounted } from 'vue'
import { Document, Bell, Setting, User } from '@element-plus/icons-vue'
import Header from './Header.vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
import '../css/message.css'

const chatRoomBotRightTop = ref<HTMLDivElement | null>(null)

interface Message {
  id: number | null;
  senderId: number;
  receiverId: number;
  message: string;
  timestamp: string;
  isNew: number;
}
interface Contact {
  id: number; 
  username: string;
  name: string;
  avatar: string;
}

interface ApiResponse<T> {
  state: boolean;
  errMessage: string | null;
  data: T[];
  token: string | null;
}

const token = localStorage.getItem('token')
const loginUser = localStorage.getItem('username')
const loginId = Number(localStorage.getItem('userId'))

const router = useRouter()
const getReplyLink = "http://localhost:8080/comment/getReply"
const getAvatarLink = "http://localhost:8080/user/getAvatar"
const getAllContactsLink = "http://localhost:8080/message/getAllContacts"
const sendMessageLink = "http://localhost:8080/message/sendMessage"
const getMessageLink = "http://localhost:8080/message/getMessage"
const getUserNameByIdLink = "http://localhost:8080/user/getUserNameById"
const updateReadLink = "http://localhost:8080/message/updateRead"
const deleteContactLink = "http://localhost:8080/message/deleteContact"

// 定义菜单项文本映射
const menuTextMap = {
  '1': '我的消息',
  '2': '回复我的',
  '3': '点赞我的',
  '4': '系统通知'
} as const

type MenuText = typeof menuTextMap[keyof typeof menuTextMap]

const selectedMenuText = ref<MenuText>(menuTextMap['1'])
const replyMessages = ref<Array<any>>([])
const contacts = ref<ApiResponse<Contact> | null>(null)
const selectedContactUsername = ref<string | null>(null) 
const selectedreceiverId = ref<number | null>(null) 

const message = ref('')
const messages = ref<Array<Message>>([])

const isChatRoomVisible = computed(() => selectedMenuText.value === menuTextMap['1'])
const isReplyMessageVisible = computed(() => selectedMenuText.value === menuTextMap['2'])
const isLikesMessageVisible = computed(() => selectedMenuText.value === menuTextMap['3'])
const isSystemNotificationVisible = computed(() => selectedMenuText.value === menuTextMap['4'])

const isAtBottom = ref(true) //记录滚动条是否在最底下，在最低的地方才刷新

const handleSelect = async (index: keyof typeof menuTextMap) => {
  selectedMenuText.value = menuTextMap[index]
  if (index === '1') {
    await getAllContacts() // 确保加载联系人和消息
  } else if (index === '2') {
    await getReply()
    stopPolling() // 停止轮询
  } else {
    stopPolling() // 停止轮询
  }
}

const getReply = async () => {
  if (!token || !loginUser) {
    router.push({ name: 'Login' })
    return
  }
  try {
    const response = await axios.post(getReplyLink, loginUser, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
    })
    const dataArray = response.data.data
    if (Array.isArray(dataArray)) {
      for (const item of dataArray) {
        const avatar = await getAvatar(item.user)
        item.avatar = avatar 
      }
      replyMessages.value = dataArray
    }
  } catch (error: unknown) {
    console.error('获取回复消息失败: ' + (error as Error).message)
  }
}

const getAvatar = async (username: string): Promise<string | undefined> => {
  try {
    const response = await axios.post(getAvatarLink, { username }, {
      headers: { 'Content-Type': 'application/json' },
    })
    if (response.data.state) {
      return response.data.data
    } else {
      console.error(response.data.errMessage)
      return undefined
    }
  } catch (error: unknown) {
    console.error('获取头像失败: ' + (error as Error).message)
    return undefined
  }
}

const goToDetailPage = (id: number) => {
  router.push({ path: `/goods/${id}` })
}

const getAllContacts = async () => {
  if (!token || !loginUser) {
    router.push({ name: 'Login' });
    return;
  }

  try {
    const response = await axios.post<ApiResponse<number>>(getAllContactsLink, loginId, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
    });

    const getUserNameById = await axios.post<ApiResponse<string>>(getUserNameByIdLink, response.data.data, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
    });

    if (getUserNameById.data.state && Array.isArray(getUserNameById.data.data)) {
      const ids: number[] = response.data.data;
      const usernames: string[] = getUserNameById.data.data;

      if (ids.length !== usernames.length) {
        console.error('IDs 和 Usernames 数量不匹配');
        contacts.value = {
          state: false,
          errMessage: 'IDs 和 Usernames 数量不匹配',
          data: [],
          token: null
        };
        return;
      }

      const contactsData = await Promise.all(usernames.map(async (username: string, index: number) => {
        const id = ids[index];
        const avatar = await getAvatar(username);
        return {
          id: id,
          username: username,
          name: username,
          avatar: avatar || ''
        };
      }));

      contacts.value = {
        state: true,
        errMessage: null,
        data: contactsData,
        token: token
      };

      if (contactsData.length > 0) {
        selectedContactUsername.value = contactsData[0].username;
        selectedreceiverId.value = contactsData[0].id
        await getMessage(contactsData[0].id);
        startPolling(contactsData[0].id);  // 启动轮询
        updateRead(contactsData[0].id)
      }
    } else {
      console.error(getUserNameById.data.errMessage);
      contacts.value = {
        state: getUserNameById.data.state,
        errMessage: getUserNameById.data.errMessage,
        data: [],
        token: token
      };
    }
  } catch (error) {
    console.error('获取联系人失败: ' + (error as Error).message);
    contacts.value = {
      state: false,
      errMessage: (error as Error).message,
      data: [],
      token: token
    };
  }
}

const onContactClick = async (username: string, id: number) => {
  selectedContactUsername.value = username
  selectedreceiverId.value = id
  await getMessage(id)
  startPolling(id) // 启动轮询
  updateRead(id)
}

const getMessage = async (id: number) => {
  if (!token || !loginUser) {
    router.push({ name: 'Login' })
    return
  }
  try {
    const messageDto = {
      sendUser: loginId,
      receiver: id,
      message: message.value
    }
    const response = await axios.post(getMessageLink, messageDto, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
    })
    if (response.data.state && Array.isArray(response.data.data)) {
        messages.value = response.data.data
    } else {
      console.error(response.data.errMessage)
    }
  } catch (error: unknown) {
    console.error('获取消息失败: ' + (error as Error).message)
  }
}

const sendMessage = async () => {
  if (!message.value.trim() || !selectedreceiverId.value) return

  try {
    const messageDto = {
      sendUser: loginId,
      receiver: selectedreceiverId.value,
      message: message.value
    }
    const response = await axios.post(sendMessageLink, messageDto, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
    })

    if (response.data.state) {
      message.value = '' // 清空输入框
      await getMessage(selectedreceiverId.value)
    } else {
      console.error(response.data.errMessage)
    }
  } catch (error: unknown) {
    console.error('发送消息失败: ' + (error as Error).message)
  }
}

const handleScroll = () => {
  const element = chatRoomBotRightTop.value
  if (element) {
    isAtBottom.value = element.scrollHeight - element.scrollTop === element.clientHeight
  }
}

const scrollToBottom = () => {
  nextTick(() => {
    const element = chatRoomBotRightTop.value
    if (element && isAtBottom.value) {
      element.scrollTop = element.scrollHeight
    }
  })
}

watch(messages, () => {
  scrollToBottom()
})

const handleKeyDown = (event: KeyboardEvent) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    sendMessage()
  }
}

const POLLING_INTERVAL = 1000

let pollingInterval: ReturnType<typeof setInterval> | null = null

const startPolling = (id: number) => {
  stopPolling()  // 确保停止之前的轮询
  pollingInterval = setInterval(async () => {
    if (id) {
      await getMessage(id)
    }
  }, POLLING_INTERVAL)
}

const stopPolling = () => {
  if (pollingInterval) {
    clearInterval(pollingInterval)
  }
}


const updateRead = async (receiver:number) => {
  const messageDto = {
      sendUser: loginId,
      receiver: receiver,
      message: message.value
    }
  try {
    const response = await axios.post(updateReadLink, messageDto, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
    })
  } catch (error) {
    console.error(message)
  }
}

const deleteContact = async (id:number)=>{
  const messageDto = {
      sendUser: loginId,
      receiver: id,
      message: message.value
    }
  try{
    const response = await axios.post(deleteContactLink, messageDto, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
    })
    if(response.status===200){
      getAllContacts()
    }
  }catch(error){
    console.error(message)
  }
}

defineProps<{
  getGoods: (filterObject: { name: string; platform: string; sortType: string; categoriesId: number }) => void;
}>();
onMounted(() => {
  getAllContacts()
  scrollToBottom()
})

onUnmounted(() => {
  stopPolling()
})
</script>
